<?php defined('SYSPATH') or die('No direct script access.');
/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2019/08/09 11:23
 * Desc: 户外活动
 */
class Controller_Pc_Api_Standard_Outdoor extends Controller_Pc_Api_Base
{


    private $_typeid = 114;   //产品类型

    public function before()
    {
        parent::before();
    }

    /**
     * 获取首页banner
     * @function
     */
    public function action_get_outdoor_banner()
    {

        $sql = "SELECT a.*,b.aid FROM sline_xcx_ads AS a LEFT JOIN sline_outdoor AS b ON a.proid=b.id WHERE a.prefix='s_outdoor_index' ORDER BY ifnull(displayorder,9999) ASC";

        $list = DB::query(1,$sql)->execute()->as_array();

        $index = 1;
        foreach($list as &$v){
            //判断产品类型
            if($v['typeid'] == $this->_typeid){
                $v['index'] = $index;
                $v['url'] = '../details/details';
                $mod = DB::select('litpic')->from('outdoor');
            }
            if(!empty($mod)){
                $row = $mod ->where('id','=',$v['proid'])->execute()->current();
                //增加图片绝对访问地址
                $v['litpic'] = Common::img($row['litpic']);
            }

            $index++;
        }

        $result['list'] = $list;
        $result['count'] = count($list);

        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);

    }

    /**
     * 获取首页导航
     * @function
     */
    public function action_get_index_nav()
    {

        $row = $this->request_body->content->row;
        $pid = $this->request_body->content->pid;
        $params = array(
            'pid'=> $pid ? $pid : 1,
            'row'=> $row ? $row : 4
        );

        $result = Model_Api_Standard_Outdoor::attr($params);
        foreach ($result['list'] as &$v)
        {
            $v['litpic'] = Model_Api_Standard_System::reorganized_resource_url($v['litpic']);
        }
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    // 获取首页产品
    public function action_get_index_outdoor()
    {
        // 获取最新活动
        $new = Model_Api_Standard_Outdoor::get_outdoor_new(0,3,0,0,0);
        foreach ($new as &$v)
        {
            $v['litpic'] = Common::img($v['litpic']);
            $v['price']  = Model_Outdoor::get_minprice($v['id'], array('info' => $v));
            $v['price']  = floatval($v['price']);
            $v['periods']= Model_Outdoor::get_bookable_periods($v['id'],1);
            $v['startDay']= isset($v['periods'][0]) ? date("m月d",$v['periods'][0]['day']): '';
        }

        // 获取热门活动
        $hot = Model_Api_Standard_Outdoor::get_outdoor_order(0,5,0,0,0);
        foreach ($hot as &$n)
        {
            $n['litpic'] = Common::img($n['litpic']);
            $n['price']  = Model_Outdoor::get_minprice($n['id'], array('info' => $n));
            $n['price'] = floatval($n['price']);
            $n['periods']= Model_Outdoor::get_bookable_periods($n['id'],1);
            $n['startDay']= isset($n['periods'][0]) ? date("m月d",$n['periods'][0]['day']): '';
            $n['attrlist'] = Model_Outdoor::line_attr($n['attrid']);
        }

        $result = array(
          'newList'=> $new,
          'hotList'=> $hot,
        );

        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    //查询条件
    public function action_query_condition()
    {
        $result = array(
            'sort' => array(
                array('id' => 0, 'name' => '综合排序'),
                array('id' => 1, 'name' => '价格从低到高'),
                array('id' => 2, 'name' => '价格从高到低'),
                array('id' => 3, 'name' => '销量最高'),
                array('id' => 4, 'name' => '产品推荐')
            ),

            'start_city' => array('name' => '出发地', 'child' => array()),
            'attribute' => array(),
            'day' => array('name' => '天数', 'child' => array()),
            'price' => array('name' => '价格', 'child' => array()),

        );
        //出发地
        $result['start_city']['child'] = DB::select('id', array('cityname', 'name'))->from('startplace')->where('isopen', '=', 1)->and_where('pid', '>', 0)->order_by('displayorder', 'asc')->execute()->as_array();
        //属性
        $result['attribute'] = DB::select('id', array('attrname', 'name'))->from('outdoor_attr')->where('pid', '=', 0)->and_where('isopen', '=', 1)->order_by(DB::expr('ifnull(displayorder,9999)'), 'asc')->execute()->as_array();
        foreach ($result['attribute'] as &$item)
        {
            $item['child'] = DB::select('id', array('attrname', 'name'))->from('outdoor_attr')->where('pid', '=', $item['id'])->and_where('isopen', '=', 1)->order_by(DB::expr('ifnull(displayorder,9999)'), 'asc')->execute()->as_array();

        }
        //天数
        $result['day']['child'] = DB::select()->from('outdoor_day')->execute()->as_array();
        $autoindex = 1;
        foreach ($result['day']['child'] as &$r)
        {
            $number = substr($r['word'], 0, 2);
            $arr = array("零", "一", "二", "三", "四", "五", "六", "七", "八", "九");
            if (strlen($number) == 1)
            {
                $days = $arr[$number];
            }
            else
            {
                if ($number == 10)
                {
                    $days = "十";
                }
                else
                {
                    if ($number < 20)
                    {
                        $days = "十";
                    }
                    else
                    {
                        $days = $arr[substr($number, 0, 1)] . "十";
                    }
                    if (substr($number, 1, 1) != "0")
                    {
                        $days .= $arr[substr($number, 1, 1)];
                    }
                }
            }
            if ($autoindex == count($result['filter']['day']['child']))
            {
                $r['name'] = $days . "日游以上";
            }
            else
            {
                $r['name'] = $days . "日游";
            }

            $autoindex++;
        }
        $result['price']['child'] = DB::select()->from('outdoor_pricelist')->where('lowerprice', '>=', 0)->order_by('lowerprice', 'asc')->execute()->as_array();

        //价格
        foreach ($result['price']['child'] as &$row)
        {
            if ($row['lowerprice'] == 0 && $row['highprice'] != 0)
            {
                $row['name'] = Currency_Tool::symbol() . $row['highprice'] . '以下';
            }
            else if ($row['highprice'] == '' || $row['highprice'] == 0)
            {
                $row['name'] = Currency_Tool::symbol() . $row['lowerprice'] . '以上';
            }
            else if ($row['lowerprice'] != '' && $row['highprice'] != '')
            {
                $row['name'] = Currency_Tool::symbol() . $row['lowerprice'] . '-' . Currency_Tool::symbol() . $row['highprice'];
            }
        }
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    /**
     * 搜索户外产品
     * @function
     */
    public function action_general_query()
    {
        $params = array(
            'pagesize' => $this->request_body->content->pagesize,
            'keyword' => $this->request_body->content->keyword,
        );
        $path = $this->request_body->content->path;
        list($params['destpy'], $params['dayid'], $params['priceid'], $params['sorttype'], , $params['startcityid'], $params['attrid'], $params['page']) = explode('-', $path);

        $result = Model_Api_Standard_Outdoor::search_result($params);
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    /**
     * 获取户外产品详情
     * @function
     */
    public function action_get_outdoor_detail()
    {
        $productid = intval($this->request_body->content->productid);
        $id = empty($productid) ? intval($this->request_body->content->id) : $productid;
        $userid = intval($this->request_body->content->userid);

        $info = DB::select()->from('outdoor')->where('webid', '=', $GLOBALS['sys_webid'])->and_where('id', '=', $id)->execute()->current();
        if(!$info)
        {// 获取产品信息失败
            $result = array('status'=> false);
            $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
        }

        $aid = $info['aid'];
        //扩展字段信息
        $extend_info = DB::select()->from('outdoor_extend_field')->where('productid', '=', $info['id'])->execute()->current();
        // 获取参与人员信息
        $member_list_info = Model_Api_Standard_Outdoor::search_order_members($info['id']);
        foreach ($member_list_info['list'] as &$memberval)
        {
            $memberval['litpic'] =  Model_Api_Standard_System::reorganized_resource_url($memberval['litpic']);
        }
        //点击率加一
        Product::update_click_rate($aid, $this->_typeid);
        $info['piclist'] = Product::pic_list($info['piclist']);
        // 处理图片路径
        foreach ($info['piclist'] as &$picv)
        {
            $picv[0] = Common::img($picv[0]);
        }
        $info['commentnum'] = Model_Comment::get_comment_num($info['id'], $this->_typeid); //评论次数
        $info['satisfyscore'] = St_Functions::get_satisfy($this->_typeid, $info['id'], $info['satisfyscore'], array('suffix' => ''));
        $info['sellnum'] = Model_Member_Order::get_sell_num($info['id'], $this->_typeid) + intval($info['bookcount']); //销售数量

        if(St_Functions::is_normal_app_install('together'))
        {
            $info['sellnum'] += Model_Together::get_virtual_member_num($this->_typeid, $info['id']);
        }

        $info['attrlist'] = Model_Outdoor_Attr::get_attrs($info['attrid']);
        $info['price'] = Model_Outdoor::get_minprice($info['id'], array('info' => $info));
        $info['iconlist'] = Product::get_ico_list($info['iconlist']);
        $info['series'] = St_Product::product_series($info['id'], $this->_typeid);
        $info['linedoc'] = unserialize($info['linedoc']);
        // 处理文档地址
        if(isset($info['linedoc']['path'][0]))
        {
            $info['linedoc']['path'][0] = Model_Api_Standard_System::reorganized_resource_url($info['linedoc']['path'][0]);
        }
        $info['all_joined_number'] = Model_Outdoor::get_all_joined_number($info['id']);
        $info['startcity_name'] = Model_Startplace::start_city($info['startcity']);
        $info['question_number'] = Model_Question::get_question_num($this->_typeid, $info['id']);
        $info['finaldest_name'] = DB::select('kindname')->from('destinations')->where('id', '=', $info['finaldestid'])->execute()->get('kindname');
        $info['bookstatus'] = Model_Outdoor::get_book_status($info);
        $info['bookstatus_name'] = Model_Outdoor::get_bookstatus_name($info['bookstatus']);

        $info['jifentprice_info'] = Model_Jifen_Price::get_used_jifentprice($info['jifentprice_id'], $this->_typeid);
        $info['jifenbook_info'] = Model_Jifen::get_used_jifenbook($info['jifenbook_id'], $this->_typeid);
        $info['jifencomment_info'] = Model_Jifen::get_used_jifencomment($this->_typeid);

        $info['gather_pos_arr'] = Model_Outdoor::get_gather_pos_arr($info['gather_pos_ids']);
        // 集合地址
        $posName = array();
        foreach ($info['gather_pos_arr'] as $pos)
        {
            array_push($posName,$pos['name']);
        }
        $info['gather_address'] = implode('、', $posName);
        //供应商
        $info['suppliers']=null;
        if($info['supplierlist'])
        {
            $info['suppliers'] = DB::query(1, "SELECT suppliername FROM `sline_supplier` WHERE id={$info['supplierlist']}")->execute()->current();
        }
        $info['guide'] = Model_Outdoor::get_guide($info['guideid']);

        // 价格循环
        $periods = Model_Outdoor::get_bookable_periods($info['id'],30);
        foreach($periods as &$perval)
        {
            $perval['startDay'] = date("m/d",strtotime($perval['date']));
            $perval['endDay']   = date("m/d",strtotime($perval['end_date']));
            $perval['period']   = Model_Outdoor::get_period($info['id'],$perval['day'],$info);
        }

        $info['supplier'] = Model_Supplier::get_supplier_info($info['supplierlist']);
        $siblings = Model_Outdoor::get_outdoors_by_group($info['groupid']);
        $attr_group = Model_Outdoor_Attr::get_attr_group($info['attrid']);

        // 获取点评信息
        $comments = Model_Comment::search_result($this->_typeid, $info['id'], null, 1, 1);
        foreach ($comments['list'] as &$commentv) // 处理封面图片
        {
            $commentv['litpic'] =  Common::img($commentv['litpic']);
        }
        // 获取提问信息
        $questions = Model_Question::search_result(1,1,0,$this->_typeid,$info['id']);
        // 更加ID查询可用的优惠券
        if(St_Functions::is_normal_app_install('coupon'))
        {
            $info['coupon_list'] = Model_Coupon::get_product_coupon_list($info['id'],$this->_typeid);
        }
        //分销赚取的金额
        if(St_Functions::is_normal_app_install('mobiledistribution'))
        {
        if(!empty($userid))
        {
            $fxgroupid = DB::select('fxgroupid')->from('fenxiao')->where("memberid",'=',$userid)->execute()->current();
            $commission_type = Model_Fenxiao_Config::get_val('cfg_fenxiao_commission_type_'.$this->_typeid,$fxgroupid['fxgroupid']);
            if($commission_type==1)
            {
                $commission_rate = Model_Fenxiao::get_commission_rate($this->_typeid,$info['id'],$fxgroupid['fxgroupid']);
                $v['commission'] =$commission_rate[0]*100;
                $v['commission'] = empty($v['commission'])?0:$v['commission'];
                $v['commission'] .='%';
                $v['profit'] = $info['price']*$commission_rate[0];
            }
            else if($commission_type==2)
            {
                $commission_rate = Model_Fenxiao::get_commission_rate_platform($this->_typeid,$info['id'],$fxgroupid['fxgroupid']);
                $v['commission'] =$commission_rate[0]*100;
                $v['commission'] = empty($v['commission'])?0:$v['commission'];
                $v['commission'] .='%';
                $temp_order = array('typeid'=>$this->_typeid,'productautoid'=>$info['id'],'totalprice'=>$info['price'],'dingnum'=>1);
                $platform_price = Model_Member_Order_Compute::caculate_platform_commission($temp_order);
                $platform_price = $platform_price==0? $info['price']:$platform_price;
                $v['profit'] = $platform_price*$commission_rate[0];
            }
            else
            {
                $commission_cash = Model_Fenxiao::get_commission_cash_line($this->_typeid,$info['id'],$fxgroupid['fxgroupid']);
                $v['commission'] = $commission_cash[0]['adult'];
                $v['commission'] = empty($v['commission'])?0:$v['commission'];
                $v['profit'] = $v['commission'];
            }
            $info['profit'] = $v['profit'];
        }
        }

        // 获取活动行程
        $info['content'] = Model_Api_Standard_Outdoor::get_detail_content(array('productinfo'=> $info,'typeid'=> $this->_typeid));
        // 处理内容
        $info['bookcontent'] = Model_Api_Standard_Xcx::filter_content($info['bookcontent']);
        $info['feeinclude']  = Model_Api_Standard_Xcx::filter_content($info['feeinclude']);
        $info['notice']      = Model_Api_Standard_Xcx::filter_content($info['notice']);

        $result = array(
            'status' => true,
            'info'   => $info,
            'comments'   => $comments,
            'questions'  => $questions,
            'extend_info'=> $extend_info,
            'periods'    => $periods,
            'siblings'   => $siblings,
            'attr_group' => $attr_group,
            'member_list_info'=> $member_list_info
        );

        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }


    /**
     * 获取日期全部套餐
     * @function
     */
    public function action_get_day_suit()
    {
        $productid = intval($this->request_body->content->productid);
        $day       = $this->request_body->content->day;

        if($day && $productid)
        {

            $sql = "SELECT a.*,b.suitname,b.description,b.childdesc,b.paytype,b.dingjin FROM sline_outdoor_suit_price AS a LEFT JOIN sline_outdoor_suit AS b ON a.suitid=b.id WHERE a.outdoorid={$productid} AND a.number<>0 AND a.day={$day} ORDER BY IFNULL(b.displayorder,9999) ASC";

            $suit = DB::query(1,$sql)->execute()->as_array();
            if(isset($suit[0]))
            {
                // 默认第一个选中
                $suit[0]['checked'] = true;
                foreach ($suit as &$suitval)
                {
                    $suitval['description'] = $suitval['description'] ? Model_Api_Standard_Xcx::filter_content($suitval['description']): '';
                }
                $result = array('status'=> true,'suit'=> $suit,'ons'=> $suit[0]['suitid']);
            }
            else
            {
                $result = array('status'=> false);
            }
        }
        else
        {
            $result = array('status'=> false);
        }

        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);

    }


    /**
     * 获取预定初始化数据
     * @function
     */
    public function action_get_order_start()
    {

        $productid = intval($this->request_body->content->productid);
        $suitid    = intval($this->request_body->content->suitid);
        $mid       = intval($this->request_body->content->mid);
        $date      = $this->request_body->content->day;
        $date      = date("Y-m-d",$date);

        $info = DB::select()->from('outdoor')->where('id', '=', $productid)->execute()->current();
        $info['price'] = Model_Outdoor::get_minprice($info['id'], array('info' => $info));
        $info['series'] = St_Product::product_series($info['id'], $this->_typeid);
        $info['tourerfields'] = Model_Outdoor_Tourer_Desc::get_tourer_fields($productid); // 游客填写字段
        $info['contract'] = Model_Contract::get_contents($info['contractid'],$this->_typeid);
        $info['agreement_open'] = $GLOBALS['cfg_outdoor_order_agreement_open'];// 户外活动协议
        $info['startcity_name'] = Model_Startplace::start_city($info['startcity']);
        $info['finaldest_name'] = DB::select('kindname')->from('destinations')->where('id', '=', $info['finaldestid'])->execute()->get('kindname');
        $jifentprice_info = Model_Jifen_Price::get_used_jifentprice($info['jifentprice_id'], $this->_typeid);
        $price_info       = Model_Outdoor::get_suit_date_price($suitid,$date,$info);
        $price_info['daystr'] = date("Y-m-d",$price_info['day']);
        $gather_point_arr = Model_Outdoor::get_gather_pos_arr($info['gather_pos_ids']);

        $suit_info = DB::select()->from('outdoor_suit')->where('id','=',$suitid)->execute()->current();
        $suit_info['paytype_name'] = Model_Member_Order::get_paytype_name($suit_info['paytype']);
        $result = array(
            'info'=> $info,
            'suit_info'=> $suit_info,
            'jifentprice_info'=> $jifentprice_info,
            'price_info'=> $price_info,
            'gather_point_arr'=> $gather_point_arr,
        );

        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }


    // 获取是否开启游客信息填写
    public function action_get_tourists()
    {
        $result = DB::select()->from('sysconfig')->where('varname', '=', 'cfg_plugin_outdoor_usetourer')->execute()->current();
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    /**
     * 创建订单
     */
    public function action_create_order()
    {

        $order = array(
            'webid' => 0,
            'addtime' => time()
        );
        if ($this->request_body->content->typeid)
        {
            $typeid = intval($this->request_body->content->typeid);
            $order['typeid'] = $typeid;
            $tmp = intval($typeid) < 10 ? '0' . $typeid : $typeid;
            $ordersn = St_Product::get_ordersn($tmp);
            $order['ordersn'] = $ordersn;

        }
        //产品id
        if ($this->request_body->content->productautoid)
        {
            $productautoid = intval($this->request_body->content->productautoid);
            $order['productautoid'] = $productautoid;
            $order['litpic'] = DB::select('litpic')->from('outdoor')->where('id', '=', $productautoid)->execute()->get('litpic');
        }
        //产品aid
        if ($this->request_body->content->productautoaid)
        {
            $productautoaid = intval($this->request_body->content->productautoaid);
            $order['productaid'] = $productautoaid;
        }
        //产品名称
        if ($this->request_body->content->productname)
        {
            $productname = Common::remove_xss($this->request_body->content->productname);
            $order['productname'] = $productname;
        }
        //成人价格
        if ($this->request_body->content->price)
        {
            $price = Common::remove_xss($this->request_body->content->price);
            $order['price'] = $price;
        }
        //小孩报价
        if ($this->request_body->content->childprice)
        {
            $childprice = Common::remove_xss($this->request_body->content->childprice);
            $order['childprice'] = $childprice;
        }
        //老人价格
        if ($this->request_body->content->oldprice)
        {
            $oldprice = Common::remove_xss($this->request_body->content->oldprice);
            $order['oldprice'] = $oldprice;
        }
        //联系人
        if ($this->request_body->content->linkman)
        {
            $linkman = Common::remove_xss($this->request_body->content->linkman);
            $order['linkman'] = $linkman;
        }
        //联系电话
        if ($this->request_body->content->linktel)
        {
            $linktel = Common::remove_xss($this->request_body->content->linktel);
            $order['linktel'] = $linktel;
        }
        // 联系邮件
        if ($this->request_body->content->linkemail)
        {
            $linkemail = Common::remove_xss($this->request_body->content->linkemail);
            $order['linkemail'] = $linkemail;
        }
        //备注说明
        if ($this->request_body->content->remark)
        {
            $remark = Common::remove_xss($this->request_body->content->remark);
            $order['remark'] = $remark;
        }
        //会员id
        if ($this->request_body->content->memberid)
        {
            $memberid = intval($this->request_body->content->memberid);
            $order['memberid'] = $memberid;
            Common::session('member', array('mid' => $memberid));
        }
        //套餐id
        if ($this->request_body->content->suitid)
        {
            $suitid = intval($this->request_body->content->suitid);
            $order['suitid'] = $suitid;
        }
        //成人数量
        if ($this->request_body->content->dingnum)
        {
            $dingnum = intval($this->request_body->content->dingnum);
            $order['dingnum'] = $dingnum;
        }
        //小孩数量
        if ($this->request_body->content->childnum)
        {
            $childnum = intval($this->request_body->content->childnum);
            $order['childnum'] = $childnum;
        }
        //老人数量
        if ($this->request_body->content->oldnum)
        {
            $oldnum = intval($this->request_body->content->oldnum);
            $order['oldnum'] = $oldnum;
        }

        //订金金额
        if ($this->request_body->content->dingjin)
        {
            $dingjin = floatval($this->request_body->content->dingjin);
            $order['dingjin'] = $dingjin;
        }
        //出发日期
        if ($this->request_body->content->usedate)
        {
            $usedate = $this->request_body->content->usedate;
            $order['usedate'] = $usedate;
        }
        //单房差
        if ($this->request_body->content->roombalance)
        {
            $roombalance = $this->request_body->content->roombalance;
            $order['roombalance'] = $roombalance;
        }
        //单房差数量
        if ($this->request_body->content->roombalancenum)
        {
            $roombalancenum = $this->request_body->content->roombalancenum;
            $order['roombalancenum'] = $roombalancenum;
        }
        //单房差支付方式
        if ($this->request_body->content->roombalance_paytype)
        {
            $roombalance_paytype = $this->request_body->content->roombalance_paytype;
            $order['roombalance_paytype'] = $roombalance_paytype;
        }

        $couponid = $this->request_body->content->couponid;
        if ($couponid)
        {
            $cid = DB::select('cid')->from('member_coupon')->where("id={$couponid}")->execute()->current();
            $totalprice = Model_Coupon::get_order_totalprice($order);
            $ischeck = Model_Coupon::check_samount($couponid, $totalprice, $order['typeid'], $order['productautoid']);
            if ($ischeck['status'] == 1)
            {
                Model_Coupon::add_coupon_order($cid, $order['ordersn'], $totalprice, $ischeck, $couponid);
            }
            else
            {
                $this->send_datagrams($this->client_info['id'], array('status' => false, 'msg' => 'coupon  verification failed!', 'ext' => array($couponid, $totalprice, $order['typeid'], $order['productautoid'])), $this->client_info['secret_key']);
                exit;
            }
        }
        $pay_way = $this->request_body->content->pay_way;
        if ($pay_way)
        {
            $order['pay_way'] = $pay_way;
        }

        //验证部分
        $validataion = Validation::factory($order);
        $validataion->rule('linktel', 'not_empty');
        $validataion->rule('linktel', 'phone');
        $validataion->rule('linkman', 'not_empty');
        if (!$validataion->check()) {
            $error = $validataion->errors();
            $keys = array_keys($validataion->errors());
            $result = array('status'=> false, 'msg'=> __("error_{$keys[0]}_{$error[$keys[0]][0]}"));
            $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
        }

        // 产品信息
        $info = DB::select()->from('outdoor')->where('id', '=', $productautoid)->execute()->current();
        if($info['status']!=3)
        {
            $result = array('status'=> false, 'msg'=> '当前产品为下架状态,不可预订');
            $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
        }

        // 判断是否需要管理员手动确认
        $query = DB::select()->from('outdoor_suit')->where('id', '=', $suitid)->and_where('outdoorid','=',$productautoid)->execute()->current();

        $need_confirm = $query['need_confirm'];
        $order['need_confirm'] = $need_confirm;

        // 套餐信息
        $suitInfo = Model_Outdoor_Suit::suit_info($order['suitid']);
        //支付方式
        $order['paytype'] = $suitInfo['paytype'];
        //产品名称
        $order['productname'] = $productname ? $productname.'('.$suitInfo['suitname'].')' : $suitInfo['suitname'];
        // 自动关闭订单时间
        $auto_close_time = $suitInfo['auto_close_time'] ? $suitInfo['auto_close_time'] : 0;
        if ($auto_close_time)
        {
            $order['auto_close_time'] = $auto_close_time + time();
        }

        // 订单来源 1PC,2WAP,3小程序,4平台添加
        $order['source'] = 3;

        // 检查是否需要填写游客
        $usetourer = DB::select()->from('sysconfig')->where('varname', '=', 'cfg_plugin_outdoor_usetourer')->execute()->current();
        // 游客信息
        if($usetourer['value'])
        {
            $tourist = $this->request_body->content->tourist;
            $tourerfields = Model_Outdoor_Tourer_Desc::get_tourer_fields($productautoid); // 游客填写字段

            //游客信息
            //获取游客信息 --开始
            $tourers = array();
            foreach ($tourist as $uk=>$uv)
            {
                $uv  = json_decode(json_encode($uv),true);
                $row = array();
                foreach ($tourerfields as $tk=>$tv)
                {
                    if($tv['fieldname'] == 'tourername')
                    {
                        $row['tourername'] = $uv['linkman'];
                    }
                    elseif ($tv['fieldname'] == 'cardnumber')
                    {
                        if($uv['cardtype'] == '出生日期')
                        {
                            $row['cardnumber'] = $uv['birth'];
                        }
                        else
                        {
                            $row['cardnumber'] = $uv['idcard'];
                        }
                    }
                    else
                    {
                        $row[$tv['fieldname']] = isset($uv[$tv['fieldname']]) ? $uv[$tv['fieldname']] : '';
                    }
                }

                $tourers[] = $row;
            }

            // 判断游客数量
            $allnum  = $dingnum + $childnum;
            $tournum = count($tourers);
            if($tournum < $allnum)
            {
                $result = array('status'=> false, 'msg'=> '请添加'.$allnum.'个游客信息');
                $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
            }
            //获取游客信息 --结束
        }


        // 拼团
        $join_id = empty($this->request_body->content->teamid) ? 0 : $this->request_body->content->teamid;

        if ($order['memberid'])
        {
            $out = Model_Api_Standard_Order::add_order($order, 'Model_Outdoor');

            if ($out['status'])
            {
                $order_id = DB::select('id')->from('member_order')->where('ordersn', '=', $order['ordersn'])->execute()->get('id');
                $order_info = Model_Member_Order::order_info($order['ordersn']);
                $order_info['orderid'] = $order_id;
                $order_info['need_confirm'] = $need_confirm;

                //添加拼团
                if(St_Functions::is_normal_app_install('together'))
                {
                    Model_Together::join_together($order['ordersn'],1,$order['productautoid'],$join_id);
                }

                // 添加户外游客信息
                Model_Outdoor_Tourer::add_tourer($order_info['id'], $tourers, $order_info['memberid']);
                //订单结算信息表数据更新
                Model_Member_Order_Compute::update($order['ordersn']);
                $result = array(
                    'status' => true,
                    'orderinfo' => $order_info
                );

                $this->send_datagrams($this->client_info['id'],$result,$this->client_info['secret_key']);
            }
            else
            {
                $result = array(
                    'status' => false,
                    'msg' => $out['msg']
                );
                $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
            }
        }
    }


    /**
     * 获取订单详情
     * @function
     */
    public function action_get_order_detail()
    {
        $id  = intval($this->request_body->content->id);
        $mid = intval($this->request_body->content->mid);

        $result = Model_Api_Standard_Outdoor::get_order_detail($id,$mid);

        if (empty($result))
        {
            $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key'], false, "查找订单信息失败", "查找订单信息失败");
        } else
        {
            $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
        }

    }

    /**
     * 确认消费
     */
    public function action_ajax_order_confirm()
    {
        $ordersn = Common::remove_xss($this->request_body->content->ordersn);
        $userid = Common::remove_xss($this->request_body->content->userid);

        if(!$ordersn || !$userid)
        {
            $result = array('status'=>0,'message'=>'操作有误');
            $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
        }
        $data = array(
            'status'=>5
        );
        $flag = DB::update('member_order')->set($data)->where('ordersn','=',$ordersn)->and_where("memberid",'=',$userid)->execute();
        if($flag)
        {
            $order = DB::select()->from('member_order')->where('ordersn', '=', $ordersn)->execute()->current();
            $status = Model_Member_Order::back_order_status_changed(2, $order, 'Model_Outdoor');
            $result = array('status'=>1, 'message'=>'确认消费成功');
        }
        else
        {
            $result = array('status'=>0, 'message'=>'操作失败');
        }

        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);

    }

    public function action_detail()
    {

        $id = intval($this->request_body->content->productid);
        $result = DB::select()->from('outdoor')->where('id', '=', $id)->execute()->current();
        $result['litpic'] =  Common::img($result['litpic']);
        if (empty($result))
        {
            $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key'], false, '查询失败', '查询失败');
        }
        else
        {
            $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
        }
        
    }

}